<?php

declare (strict_types=1);

namespace magein\think\pay;

use magein\pay\extension\WxOauthInterface;
use magein\pay\PayConfig;
use think\facade\Cache;

class PayWxOauth implements WxOauthInterface
{

    /**
     * 获取微信回调地址
     * @param $data
     * @return string
     */
    public function getOauthRedirect($data): string
    {
        $domain = PayConfig::domain();

        $account = $data['account'] ?? '';
        $pay_no = $data['pay_no'] ?? '';

        return sprintf('%s/pay/oauth/%s/%s', $domain, $account, $pay_no);
    }

    /**
     * 获取缓存名称
     * @param $data
     * @return string
     */
    public function getCacheName($data): string
    {
        $channel_id = $data['channel_id'] ?? '';
        $user_id = $data['user_id'] ?? '';

        return 'pay_wx_open_id_' . $channel_id . $user_id;
    }

    /**
     * 获取授权id
     * @param $data
     * @return string
     */
    public function getWxOpenId($data): string
    {
        $name = $this->getCacheName($data);

        return $name ? Cache::get($name, '') : '';
    }

    /**
     * 设置openid
     * @param $data
     * @return bool
     */
    public function setWxOpenId($data): bool
    {
        $name = $this->getCacheName($data);

        $open_id = $data['open_id'] ?? '';

        if ($open_id) {
            Cache::tag('pay_tag_wx_open_id')->set($name, $open_id, 86400);
        }

        return true;
    }
}